<template>
	<view class="product-list-container">
		<!-- 顶部导航栏 -->
		<view class="nav-header">
			<view class="nav-left" @click="goBack">
				<view class="nav-back-btn">
					<text class="nav-icon">‹</text>
				</view>
			</view>
			<view class="nav-center">
				<text class="nav-title">{{ categoryName }}</text>
			</view>
			<view class="nav-right" @click="goToSearch">
				<view class="nav-search-btn">
					<text class="nav-icon">🔍</text>
				</view>
			</view>
		</view>
		
		<!-- 筛选排序栏 -->
		<view class="filter-bar">
			<view 
				v-for="(filter, index) in filterOptions" 
				:key="index"
				class="filter-item"
				:class="{ 'filter-active': selectedFilter === filter.value }"
				@click="selectFilter(filter.value)"
			>
				<text class="filter-text">{{ filter.label }}</text>
			</view>
		</view>
		
		<!-- 商品列表 -->
		<scroll-view class="product-scroll" scroll-y="true" @scrolltolower="loadMore">
			<view class="product-grid">
				<view
					v-for="(product, index) in products"
					:key="product.productId"
					class="product-item"
					@click="goToProduct(product)"
				>
					<!-- 商品图片 -->
					<view class="product-image">
						<image
							v-if="product.pic && product.pic.length > 0"
							:src="product.pic[0]"
							class="product-img"
							mode="aspectFill"
						/>
						<view v-else class="image-placeholder">
							<text class="image-icon">🏔️</text>
						</view>
					</view>

					<!-- 商品信息 -->
					<view class="product-info">
						<text class="product-name">{{ product.name }}</text>
						<view class="product-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ product.price }}</text>
						</view>
						<view class="product-stats">
							<text class="stats-text">已售{{ product.salesCount || 0 }}</text>
							<view class="rating">
								<text class="rating-icon">⭐</text>
								<text class="rating-value">{{ product.avgScore || 0 }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 加载更多 -->
			<view v-if="hasMore" class="load-more">
				<text class="load-text">{{ isLoading ? '加载中...' : '上拉加载更多' }}</text>
			</view>
			
			<!-- 没有更多 -->
			<view v-else-if="products.length > 0" class="no-more">
				<text class="no-more-text">已显示全部商品</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { productApi } from '@/api'

// 页面参数
const categoryId = ref('')
const categoryName = ref('分类名称')

// 响应式数据
const products = ref([])
const selectedFilter = ref('comprehensive')
const isLoading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(20)

// 筛选选项
const filterOptions = ref([
	{ label: '综合', value: 'comprehensive', sort: 0 },
	{ label: '销量', value: 'sales', sort: 1 },
	{ label: '评价', value: 'rating', sort: 2 },
	{ label: '价格', value: 'price', sort: 3 }
])

// 页面参数处理
onLoad((options) => {
	console.log('页面参数:', options)

	if (options.categoryId) {
		categoryId.value = options.categoryId
	}
	if (options.categoryName) {
		categoryName.value = decodeURIComponent(options.categoryName)
	}

	// 重置数据并加载商品
	resetData()
	loadProducts()
})

// 页面加载
onMounted(() => {
	// onLoad会在onMounted之前执行，这里作为备用
	if (!categoryId.value) {
		console.log('未获取到categoryId，加载默认商品列表')
		loadProducts()
	}
})

// 重置数据
const resetData = () => {
	products.value = []
	currentPage.value = 1
	hasMore.value = true
	isLoading.value = false
}

// 加载商品
const loadProducts = async (isLoadMore = false) => {
	if (isLoading.value) return

	try {
		isLoading.value = true

		if (!isLoadMore) {
			currentPage.value = 1
			products.value = []
		}

		// 获取当前选中的排序方式
		const currentFilter = filterOptions.value.find(item => item.value === selectedFilter.value)
		const sortValue = currentFilter ? currentFilter.sort : 0

		const params = {
			pageNum: currentPage.value,
			pageSize: pageSize.value,
			level2Id: categoryId.value || null,
			sort: sortValue
		}

		console.log('请求参数:', params)

		const response = await productApi.getProductList(params)
		console.log('商品列表响应:', response)

		if (response && response.records) {
			if (isLoadMore) {
				products.value = [...products.value, ...response.records]
			} else {
				products.value = response.records
			}

			// 判断是否还有更多数据
			hasMore.value = currentPage.value < response.pages
		}

	} catch (error) {
		console.error('加载商品列表失败:', error)
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

// 筛选选择
const selectFilter = (filterValue) => {
	selectedFilter.value = filterValue
	// 重新加载商品数据
	loadProducts()
}

// 加载更多
const loadMore = () => {
	if (!isLoading.value && hasMore.value) {
		currentPage.value++
		loadProducts(true)
	}
}

// 页面跳转
const goBack = () => {
	// 直接使用 switchTab 跳转到分类首页，确保能正确返回
	uni.switchTab({
		url: '/pages/category/index'
	})
}

const goToSearch = () => {
	uni.navigateTo({
		url: '/pages/search/index'
	})
}

const goToProduct = (product) => {
	uni.navigateTo({
		url: `/pages/product/detail?productId=${product.productId}`
	})
}

// 注意：使用onLoad生命周期钩子后不需要再暴露方法
</script>

<style lang="scss" scoped>
.product-list-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background: #F5F5F5;
}

.nav-header {
	background: #FFFFFF;
	padding: 12px 15px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-bottom: 1px solid #E5E5E5;
	position: relative;
}

.nav-left,
.nav-right {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 40px;
	height: 40px;
}

.nav-back-btn,
.nav-search-btn {
	width: 32px;
	height: 32px;
	background: #F8F9FA;
	border-radius: 16px;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: background-color 0.2s ease;
	
	&:active {
		background: #E9ECEF;
	}
}

.nav-icon {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
}

.nav-center {
	flex: 1;
	text-align: center;
	padding: 0 15px;
}

.nav-title {
	font-size: 17px;
	font-weight: 500;
	color: #333333;
}

.filter-bar {
	background: #FFFFFF;
	padding: 12px 15px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1px solid #F0F0F0;
}

.filter-item {
	position: relative;
	padding: 8px 12px;
	flex: 1;
	text-align: center;
}

.filter-text {
	font-size: 15px;
	color: #666666;
}

.filter-active {
	.filter-text {
		color: #333333;
		font-weight: 600;
	}

	&::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 20px;
		height: 2px;
		background: #4FACFE;
	}
}

.product-scroll {
	flex: 1;
	padding: 15px;
}

.product-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	justify-content: space-between;
}

.product-item {
	width: calc(50% - 5px);
	background: #FFFFFF;
	border-radius: 8px;
	overflow: hidden;
	margin-bottom: 15px;
}

.product-image {
	width: 100%;
	height: 140px;
	position: relative;
}

.product-img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.image-placeholder {
	width: 100%;
	height: 100%;
	background: #E5E5E5;
	display: flex;
	align-items: center;
	justify-content: center;
}

.image-icon {
	font-size: 32px;
	color: #CCCCCC;
}

.product-info {
	padding: 12px;
}

.product-name {
	font-size: 14px;
	color: #333333;
	margin-bottom: 8px;
	display: block;
}

.product-price {
	display: flex;
	align-items: baseline;
	margin-bottom: 8px;
}

.price-symbol {
	font-size: 12px;
	color: #FF4757;
}

.price-value {
	font-size: 16px;
	font-weight: 600;
	color: #FF4757;
}

.product-stats {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.stats-text {
	font-size: 12px;
	color: #999999;
}

.rating {
	display: flex;
	align-items: center;
	gap: 2px;
}

.rating-icon {
	font-size: 12px;
	color: #FFD700;
}

.rating-value {
	font-size: 12px;
	color: #999999;
}

.load-more,
.no-more {
	text-align: center;
	padding: 20px;
}

.load-text,
.no-more-text {
	font-size: 14px;
	color: #999999;
}
</style>
